package com.wing.storage.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.chanjet.entity.inventory.CurrentStockResponse;
import com.wing.chanjet.entity.inventory.InventoryClassResponse;
import com.wing.chanjet.feign.ChanjetClient;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.response.ProductVO;
import com.wing.product.service.ProductDetailService;
import com.wing.res.model.response.ProductCountInWarhouseVo;
import com.wing.storage.dao.ProductInventoryDao;
import com.wing.storage.dao.ProductInventoryDetailDao;
import com.wing.storage.model.entity.ProductInventory;
import com.wing.storage.model.entity.ProductInventoryDetail;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品库存-ServiceImpl
 *
 * @author xiayang
 */
@Service
@Slf4j
public class ProductInventoryServiceImpl extends ServiceImpl<ProductInventoryDao, ProductInventory> implements ProductInventoryService {

    @Resource
    ProductInventoryDetailDao productInventoryDetailDao;

    @Resource
    ProductDetailService productDetailService;

    @Resource
    ChanjetClient chanjetClient;

    @Override
    public Page<ProductInventory> pageList(Page page, Map<String, Object> params) {
        List<ProductInventory> list = baseMapper.pageList(page, params);
        // 产品库存详细列表
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, Object> paramsDetail = new HashMap<>();
            paramsDetail.put("productInventoryIdList", list.stream().map(l -> l.getId()).collect(Collectors.toList()));
            List<ProductInventoryDetail> detailList = productInventoryDetailDao.list(paramsDetail);
            if (CollectionUtil.isNotEmpty(detailList)) {
                list.stream().forEach(l-> {
                    l.setProductInventoryDetailList(
                        detailList.stream()
                            .filter(d -> l.getId().equals(d.getProductInventoryId()))
                            .collect(Collectors.toList())
                    );
                });
            }
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductInventory get(Long productInventoryId) {
        return baseMapper.get(productInventoryId);
    }

    @Override
    public void chanjetCurrentStockSync() {
        //物料列表2
        List<ProductDetail> productDetailList = productDetailService.list();
        //库存列表
        List<ProductInventory> list = this.list();
        //现存量列表
        JsonResult<List<CurrentStockResponse>> jsonResult = chanjetClient.currentStockQuery();

        List<ProductInventory> productInventoryList = new ArrayList<>();

        if (jsonResult.getCode() == 200) {
            List<CurrentStockResponse> currentStockList = jsonResult.getData();
            for (CurrentStockResponse currentStock : currentStockList) {
                ProductInventory productInventory = new ProductInventory();
                //物料
                ProductDetail productDetail = productDetailList.stream().filter(t -> t.getSkuCode().equals(currentStock.getInventoryCode())
                        && t.getSkuName().equals(currentStock.getInventoryName())
                        && t.getSkuSpec().equals(currentStock.getSpecification())).findFirst().orElse(null);
                if (productDetail != null) {
                    productInventory.setProductDetailId(productDetail.getId());
                } else {
                    throw new BusinessException("物料不存在");
                }
                productInventory.setQuantity(new BigDecimal(currentStock.getExistingQuantity()));
                productInventory.setCreateTime(LocalDateTime.now());
                productInventory.setCreator(JwtUtils.getLoginUserId());
                productInventory.setCreatorName(JwtUtils.getLoginUsername());

                ProductInventory inventory = list.stream().filter(t -> t.getProductDetailId().longValue() == productInventory.getProductDetailId().longValue()).findFirst().orElse(null);
                if(inventory != null){
                    productInventory.setId(inventory.getId());
                }
                productInventoryList.add(productInventory);
            }
            this.saveOrUpdateBatch(productInventoryList);
        }
    }

    /**
     * 查询物料的库存数量
     * @return
     */
    @Override
    public List<ProductCountInWarhouseVo> getProductCountInWarhouse() {
        return baseMapper.getProductCountInWarhouse();
    }

    @Override
    public List<ProductVO> selProductInventory(Map<String, Object> params) {
        List<ProductVO> list = baseMapper.pageList2(params);
        return list;
    }

}
